import { Navigate, useRoutes } from 'react-router-dom';
// import Login from "@/views/login/inedx";
import React, { Children } from 'react';
import lazyLoad from './utils/lazyLoad';
import { RouteObject } from './interface';
import { store } from '@/redux';
import { LayoutIndex } from './constant';
import NoPermission from '@/views/errorPage/403';
import NoFound from '@/views/errorPage/404';

// 导入modules 文件下的路由文件
const metaRouters = import.meta.glob('./modules/**/*.tsx', { eager: true });

// 处理路由
export const routerArray: RouteObject[] = [];
Object.keys(metaRouters).forEach((item: string) => {
  Object.keys(metaRouters[item] as any).forEach((key) => {
    routerArray.push(...(metaRouters[item] as any)[key]);
  });
});

// 处理访问根目录时是否跳转到login
// function AuthWrapper() {
//   function handleAuthCheck() {
//     // 从store中获取tokne
//     const userToken = store.getState().global.token;

//     if (userToken) {
//       return <Navigate to='/sys/user' />;
//     } else {
//       return <Navigate to='/login' />;
//     }
//   }
//   return handleAuthCheck();
// }

export const rootRouter = [
  {
    path: '/',
    // 访问首页跳转到登陆页
    element: <Navigate to='/login' />,
  },
  {
    path: '/login',
    // element: <Login />,
    element: lazyLoad(React.lazy(() => import('@/views/login/inedx'))),
    meta: {
      // 判断是否需要登录验证
      requireAuth: false,
      title: '登录',
      key: 'login',
    },
  },
  {
    element: <LayoutIndex />,
    meta: {
      title: 'Loading',
    },
    children: [
      {
        path: '/loading',
        element: lazyLoad(React.lazy(() => import('@/views/loading/index'))),
        meta: {
          title: 'Loading',
          key: '/loading',
        },
      },
    ],
  },
  ...routerArray,
  {
    path: '/403',
    element: <NoPermission />,
  },
  {
    path: '*',
    element: <Navigate to='/404' />,
  },
  {
    path: '/404',
    element: <NoFound />,
  },
];

const Router = () => {
  const routes = useRoutes(rootRouter);
  return routes;
};

export default Router;
